<?php


namespace app\admin\controller;

use app\logic\ArticleHelper;
use app\logic\DataHelper;
use app\logic\MenuHelper;
use think\facade\Db;
use think\facade\View;

class Article extends Base
{
    public function index() {
        return View::fetch('index');
    }

    public function save() {
        $params = get_all_params();


        if (!check_params_empty(['title'])) {
            return json([ 'code' => -1, 'msg' => '请填写：标题' ]);
        }

        $params['category_name'] = DataHelper::get_value('tb_article_category', "id=".$params['category_id'], "title");

        if (isset($params['id']) && $params['id'] > 0) {
            //更新
            DataHelper::update('tb_article', "id=".$params['id'], $params);
        } else {
            //新增
            DataHelper::add('tb_article', $params);
        }

        return json([ 'code' => 0, 'msg' => '成功' ]);
    }

    public function edit($id = 0) {
        if ($id > 0) {
            $entry = DataHelper::find_by_id('tb_article', $id);
        } else {
            $entry = [
                'id' => 0,
                'title' => '',
                'body' => '',
                'category_id' => '',
                'status' => 0,
                'idx' => 0
            ];
        }

        /*$category_list = DataHelper::select("tb_article_category", "status=0", [
            "order_by" => "pid asc,idx desc"
        ]);*/

        $category_list = ArticleHelper::get_article_category_as_combobox();

        return View::fetch('edit', [
            'entry' => $entry,
            'category_list' => $category_list
        ]);
    }

    public function list($title = '', $page = 1, $limit = 20) {
        $query = " status=0 ";

        if (!empty($title)) {
            $query .= " and title like '%$title%' ";
        }


        list($list, $count) = DataHelper::select_page('tb_article', $query, [ 'page' => $page, 'limit' => $limit ]);

        if ($count <= 0) {
            return json([ 'code' => 201, 'msg' => '没有相关数据' ]);
        }

        return json([
            'code' => 0,
            'msg' => '成功',
            'count' => $count,
            'data' => $list
        ]);
    }

    public function del() {
        $params = get_all_params();
        $ids = $params['ids'];

        DataHelper::update('tb_article', "id in ($ids)", [
            'status' => -1
        ]);
        return json([ 'code' => 0, 'msg' => '成功' ]);
    }
}